package com.nhim.cms.dao;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceException;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.stereotype.Repository;

import com.nhim.cms.domain.Content;
import com.nhim.core.AppContext;
import com.nhim.core.dao.CoreDAO;
@Repository
public class ContentDAO extends CoreDAO<Integer,Content> implements IContentDAO {
	
	// property constants
	public static final String ARCHIVED = "archived";
	public static final String CREATE_DATE = "createDate";

	@Autowired
	EntityManagerFactory entityManagerFactory;

	@PostConstruct
	public void init() {
		super.setEntityManagerFactory(entityManagerFactory);
	}


	public static IContentDAO getFromApplicationContext(
			ApplicationContext ctx) {
		return (IContentDAO) ctx.getBean(ContentDAO.class);
	}
	public static IContentDAO getInstance() {
		return getFromApplicationContext(AppContext.getApplicationContext());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Content> findByProperty(String propertyName,
			final Object value) {
		try {

			final String queryString = "select model from Content model where model."
					+ propertyName + "= :propertyValue";
			return getJpaTemplate().executeFind(new JpaCallback<Object>() {

				public Object doInJpa(EntityManager em)
						throws PersistenceException {
					Query query = em.createQuery(queryString);
					query.setParameter("propertyValue", value);
					return query.getResultList();
				}
			});
		} catch (RuntimeException re) {
			throw re;
		}
	}

}
